"""
股票相关API路由
"""
from flask import Blueprint, jsonify, request, Response
import json
from datetime import datetime

from services.data_service import DataService
from services.technical_analysis import TechnicalAnalysis
from services.ai_service import AIService
from services.search_service import SearchService
from utils.errors import (
    handle_stock_data_error, handle_financial_data_error,
    handle_risk_analysis_error, handle_ai_analysis_error,
    handle_investment_recommendation_error, handle_chart_data_error,
    handle_stream_error, ValidationError
)
from utils.helpers import (
    format_stock_info, format_financial_metrics,
    build_analysis_data_dict, add_technical_indicators_to_analysis,
    build_comprehensive_analysis_data
)

# 创建蓝图
stock_bp = Blueprint('stock', __name__, url_prefix='/api/stock')


@stock_bp.route('/<symbol>', methods=['GET'])
def get_stock_info(symbol):
    """获取股票基本信息"""
    try:
        info = DataService.get_stock_info(symbol)
        result = format_stock_info(info, symbol)
        return jsonify(result)
    except Exception as e:
        return handle_stock_data_error(e, symbol)


@stock_bp.route('/<symbol>/financials', methods=['GET'])
def get_financial_metrics(symbol):
    """获取财务指标"""
    try:
        info = DataService.get_stock_info(symbol)
        result = format_financial_metrics(info, symbol)
        return jsonify(result)
    except Exception as e:
        return handle_financial_data_error(e, symbol)


@stock_bp.route('/<symbol>/risk', methods=['GET'])
def get_risk_analysis(symbol):
    """获取风险评估"""
    try:
        stock_data = DataService.get_historical_data(symbol)
        result = TechnicalAnalysis.calculate_risk_metrics(stock_data)
        result['symbol'] = symbol
        return jsonify(result)
    except Exception as e:
        return handle_risk_analysis_error(e, symbol)


@stock_bp.route('/<symbol>/chart', methods=['GET'])
def get_chart_data(symbol):
    """获取图表数据"""
    try:
        stock_data = DataService.get_historical_data(symbol)
        result = TechnicalAnalysis.calculate_chart_data(stock_data)
        result['symbol'] = symbol
        return jsonify(result)
    except Exception as e:
        return handle_chart_data_error(e, symbol)


@stock_bp.route('/<symbol>/recommendation', methods=['GET'])
def get_investment_recommendation(symbol):
    """获取投资建议"""
    try:
        info, stock_data = DataService.get_financial_data(symbol)
        result = TechnicalAnalysis.calculate_investment_recommendation(info, stock_data)
        result['symbol'] = symbol
        return jsonify(result)
    except Exception as e:
        return handle_investment_recommendation_error(e, symbol)


@stock_bp.route('/<symbol>/ai-analysis-stream', methods=['POST'])
def get_ai_analysis_stream(symbol):
    """获取AI投资分析 - 流式响应"""
    try:
        # 获取请求数据
        data = request.get_json()
        question = data.get('question', '')
        analysis_type = data.get('analysis_type', 'comprehensive')
        conversation_history = data.get('conversation_history', [])

        if not question.strip():
            return jsonify({'error': 'Question is required'}), 400

        # 获取股票数据
        info, stock_data = DataService.get_financial_data(symbol)

        # 构建完整分析数据
        analysis_data = build_comprehensive_analysis_data(
            symbol, info, stock_data, question, analysis_type, conversation_history
        )

        # 构建AI分析提示词
        prompt = AIService.build_specialized_analysis_prompt(analysis_data)

        # 构建对话消息（包含历史对话）
        messages = [
            {
                'role': 'system',
                'content': '你是一位专业的股票投资分析师，具有丰富的财务分析经验和市场洞察力。请基于提供的数据进行客观、专业的分析。回答要简洁明了，使用markdown格式，包含适当的标题、列表和重点标记。'
            }
        ]

        # 添加对话历史（限制最近几条）
        for msg in conversation_history[-4:]:  # 只保留最近4条对话
            if msg.get('role') and msg.get('content'):
                messages.append({
                    'role': msg['role'],
                    'content': msg['content']
                })
        print(f"{prompt}")
        # 添加当前问题
        messages.append({
            'role': 'user',
            'content': prompt
        })

        # 流式生成响应
        def generate():
            try:
                for chunk in AIService.stream_ai_response(messages):
                    yield f"data: {chunk}\n\n".encode('utf-8')
                yield f"data: [DONE]\n\n".encode('utf-8')
            except Exception as e:
                yield f"data: {handle_stream_error(e)}\n\n".encode('utf-8')
                yield f"data: [DONE]\n\n".encode('utf-8')

        return Response(
            generate(),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache, no-store, must-revalidate',
                'Pragma': 'no-cache',
                'Expires': '0',
                'Connection': 'keep-alive',
                'Access-Control-Allow-Origin': '*',
                'Access-Control-Allow-Headers': 'Cache-Control, Content-Type',
                'X-Accel-Buffering': 'no',
                'X-Content-Type-Options': 'nosniff',
                'Content-Encoding': 'identity',
                'Transfer-Encoding': 'chunked'
            },
            direct_passthrough=True
        )

    except Exception as e:
        return jsonify({
            'error': 'Failed to start AI analysis stream',
            'details': str(e),
            'symbol': symbol
        }), 500


@stock_bp.route('/search', methods=['GET'])
def search_stocks():
    """搜索股票代码和名称"""
    try:
        query = request.args.get('q', '').strip()
        limit = int(request.args.get('limit', 10))

        if not query:
            return jsonify({
                'error': 'Query parameter is required',
                'suggestions': []
            }), 400

        results = SearchService.search_stocks(query, limit)

        return jsonify({
            'query': query,
            'suggestions': results,
            'total': len(results)
        })

    except Exception as e:
        return jsonify({
            'error': 'Search failed',
            'details': str(e),
            'suggestions': []
        }), 500